package com.kdtech.analyse.blog;
import com.kdtech.crawler.CrawlHTML;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.analyse.AnalyseNews;

public class CnfolBlogAnalyse implements AnalyseNews{

	//http://blog.cnfol.com/dy163ccdpfk/article/1351486480-83330561.html
	//http://new.blog.cnfol.com/zjnb25851998/article/1389152916-91372482.html
	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://blog.cnfol.com/.*/article/[0-9]*-[0-9]*.html",
				"http://new.blog.cnfol.com/.*/article/[0-9]*-[0-9]*.html"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		String html = urlMeta.getHtml();
		if (html== null) {
		}
		NewsMeta blog = new NewsMeta();
		blog.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		String author = null;

		Document doc = Jsoup.parse(html);
		if(url.startsWith("http://new.blog")){
			title = doc.select("div.ArticleBox h1 a").text();
			date = DateUtils.matchDate(doc.select("span.MBTime").text());
			content = HtmlCleaner.getContentHtml(url,  doc.select("div.ArticleCont"));
			author = doc.select("div#footer.NewFooter> center:eq(0) >a").text();
		}else{
			if(StringUtils.isBlank(author))  author = doc.select("div#footer.NewFooter> center:eq(0) >a").text();
			if(StringUtils.isBlank(author)) 	author = doc.select("a#BlogNameLoad").text();
			title  = doc.select("title").text();
			if (title.contains("_")) title = StringUtils.substringBefore(title, "_");
			date = DateUtils.matchDate(doc.select(".MBTime").text());
			content = HtmlCleaner.getContentHtml(url,  doc.select(".ArticleCont"));
		}
		blog.setAuthor(author);
		blog.setTitle(title);
		blog.setContent(content);
		blog.setDate(date);
		return blog;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}





	public static void main(String[] args) throws UnsupportedEncodingException {
		String url = "http://blog.cnfol.com/gqingyou/article/1405314765-94952995.html";
		CnfolBlogAnalyse test = new CnfolBlogAnalyse();
		if(test.isDetailPage(url)){
			UrlMeta responseToURL = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = test.parserHtml(responseToURL);
			System.out.println(parserHtml);
//			System.out.println(test.Update(parserHtml));
		}else{
			System.out.println("不符合规则");
		}
	}
	

}
